import React, { useState, useEffect, useRef } from "react";
import { VOICE_CONFIG } from "@/constant/config";
import { Popup, Toast } from "antd-mobile";
import styles from "./voice.module.scss";
import VoiceIcon from "../icons/voice.svg";
import StopIcon from "../icons/stop.svg";
import WebAudioSpeechRecognizer from "@/utils/speechrecognizer.js";
import { isWebView, isIosApp, isAndroidApp } from "@/utils/utils";
import {
  useVoicePermission,
  showVoicePermissionErrMsg,
} from "@/hooks/useMicrophonePermission";

export const Voice = (props: {
  visible: boolean;
  onClose: () => void;
  onSubmit: (text: string) => void;
  setUserInput: (text: string) => void;
}) => {
  const [isRecording, setIsRecording] = useState(false);
  const [recognitionResult, setRecognitionResult] = useState("");
  const [error, setError] = useState(null);
  const webAudioSpeechRecognizerRef = useRef<any>(null);

  const { hasVoicePermission, requestVoicePermission } = useVoicePermission();
  const params = {
    // signCallback: signCallback, // 鉴权函数，若直接使用默认鉴权函数。可不传此参数
    // 用户参数
    secretid: VOICE_CONFIG.secretId,
    secretkey: VOICE_CONFIG.secretKey,
    appid: VOICE_CONFIG.appId,
    // 临时密钥参数，非必填
    // token: config.token,
    // 实时识别接口参数
    engine_model_type: "16k_zh", // 因为内置WebRecorder采样16k的数据，所以参数 engineModelType 需要选择16k的引擎，为 '16k_zh'
    // 以下为非必填参数，可跟据业务自行修改
    // voice_format : 1,
    // hotword_id : '08003a00000000000000000000000000',
    // needvad: 1,
    // filter_dirty: 1,
    // filter_modal: 2,
    // filter_punc: 0,
    // convert_num_mode : 1,
    // word_info: 2
  };

  const startRecognition = () => {
    webAudioSpeechRecognizerRef.current = new WebAudioSpeechRecognizer(params);
    setIsRecording(true);

    webAudioSpeechRecognizerRef.current.OnRecognitionStart = (res: any) => {
      console.log("开始识别", res);
    };

    webAudioSpeechRecognizerRef.current.OnSentenceBegin = (res: any) => {
      console.log("一句话开始", res);
      setIsRecording(true);
    };

    webAudioSpeechRecognizerRef.current.OnRecognitionResultChange = (
      res: any,
    ) => {
      console.log("识别变化时", res.result.voice_text_str);
      // props.setUserInput(res.result.voice_text_str);
    };

    webAudioSpeechRecognizerRef.current.OnSentenceEnd = (res: any) => {
      console.log("一句话结束", res.result.voice_text_str);
      props.setUserInput(res.result.voice_text_str);
    };

    webAudioSpeechRecognizerRef.current.OnRecognitionComplete = (res: any) => {
      console.log("识别结束", res);
      setIsRecording(false);
    };

    webAudioSpeechRecognizerRef.current.OnError = (res: any) => {
      console.log("识别失败", res);
      setError(res);
      setIsRecording(false);
    };

    webAudioSpeechRecognizerRef.current.start();
  };
  const stopRecognition = () => {
    if (webAudioSpeechRecognizerRef.current && isRecording) {
      webAudioSpeechRecognizerRef.current.stop();
      onSubmit();
    }
  };
  const onStart = async (e: any) => {
    console.log("🚀 ~ onStart ~ e:", e);
    e.stopPropagation();
    if (!hasVoicePermission) {
      return showVoicePermissionErrMsg();
    }
    // await checkPermission();
    startRecognition();
  };
  const onStop = (e: any) => {
    e.stopPropagation();
    stopRecognition();
  };
  const onSubmit = () => {
    console.log(recognitionResult, "recognitionResult");
    props.onSubmit(recognitionResult);
    setIsRecording(false);
  };
  const onClose = () => {
    props.onClose();
    setIsRecording(false);
  };
  useEffect(() => {
    requestVoicePermission();
  }, []);
  return (
    <Popup
      className="voice-popup"
      visible={props.visible}
      onMaskClick={() => {
        onClose();
      }}
      onClose={() => {
        onClose();
      }}
      bodyStyle={{
        height: "40vh",
      }}
      onClick={onClose}
    >
      {isRecording ? (
        <div className={styles["voice-wrap"]}>
          <div>{recognitionResult}</div>
          <div
            className={`${styles["voice-button"]} ${styles["voice-button-stop"]}`}
            onClick={onStop}
          >
            <StopIcon
              className={`${styles["voice-button-icon"]} ${styles["pulse"]}`}
            />
            <div></div>
          </div>
          <div className={styles["voice-button-txt"]}>停止录制</div>
        </div>
      ) : (
        <div className={styles["voice-wrap"]}>
          <div className={styles["voice-button"]} onClick={onStart}>
            <VoiceIcon className={styles["voice-button-icon"]} />
          </div>
          <div className={styles["voice-button-txt"]}>点击说话</div>
        </div>
      )}
      {/* {error && <div>Error: {JSON.stringify(error)}</div>} */}
    </Popup>
  );
};
